﻿package {
	import flash.display.DisplayObject;	
    import flash.display.MovieClip; 
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Matrix;
	
	public class rateRound extends mc_fx {
		private var _moveTo	: Point;
		private var _roll	: Number;
		private var _focus	: Boolean;
		private var _rounds	: Array;
		private var _tailRoll: Number;
		
		function rateRound(): void {
			super();
			_roll	= 0;
			direct 	= 1;
			_focus	= false;
			
			createTail();
			
			addEvent(MouseEvent.ROLL_OVER, doOver);
			addEvent(MouseEvent.ROLL_OUT, doOut);
			addEvent(Event.ENTER_FRAME, doFrame);
		}
		
		protected function createTail(): void {
			_rounds 	= new Array();
			_tailRoll 	= 0;
			var _index: int = parent.getChildIndex(this);
			for (var i:int=0; i<10; i++) {
				var rr: rr_round = new rr_round();
				rr._data = {
					p		: new Point()
				};
				_rounds.push(rr);
				parent.addChildAt(rr, _index);
			}
		}
		
		protected function updateTail(): void {
			_tailRoll += 0.1;
			var mt: Point = new Point(x, y);
			for (var i: int=0; i<_rounds.length; i++) {
				_rounds[i]._data.p.x += (mt.x - _rounds[i]._data.p.x) / (2 + i * 4);
				_rounds[i]._data.p.y += (mt.y - _rounds[i]._data.p.y) / (2 + i * 4);
				var mat: Matrix = new Matrix();
				var scale: Number = 1/(1.4 + i);
				mat.scale(scale, scale);
				mat.translate(5, 0);
				mat.rotate(_tailRoll - i/_rounds.length * Math.PI);
				mat.translate(_rounds[i]._data.p.x, _rounds[i]._data.p.y);
				_rounds[i].transform.matrix = mat;
			}
		}
		
		protected function doOver(e: Event): void {
			focus = true;
		}
		
		protected function doOut(e: Event): void {
			focus = false;
		}
		
		public function get direct(): int {
			return this['kl1'].visible?1:-1;
		}
		
		public function get focus(): Boolean {
			return _focus;
		}

		public function set focus(a_focus: Boolean): void {
			if (_focus != a_focus) {
				_focus = a_focus;
				if (focus) 
					_moveTo = rollCenter; 
			}
		}

		public function set direct(a_direct: int): void {
			if (direct != a_direct) {
				if (a_direct == -1) {
					this['kl1'].visible = false;
					this['kr1'].visible = false;
					this['kl2'].visible = true;
					this['kr2'].visible = true;
				} else if (a_direct == 1) {
					this['kl1'].visible = true;
					this['kr1'].visible = true;
					this['kl2'].visible = false;
					this['kr2'].visible = false;
				}
			}
		}
		
		public function get rollCenter(): Point {
			return new Point(parent.mouseX, parent.mouseY);
		}
		
		public function doFrame(e: Event): void {
			if (!focus) {
				_roll += 0.02;
				_moveTo = rollCenter.add(Point.polar(150, _roll));
				if (_moveTo.x - x > 0) 
					direct = 1
				else direct = -1;
			}
			x += (_moveTo.x - x) / 30;
			y += (_moveTo.y - y) / 30;
			updateTail();
		}
	}
}